#!/bin/bash
# 
# 启动screen的进程数

maxProc=5
#scree名字前缀
scrPrefix='topoSA出队'

#颜色字
function msg(){
	local msg=$1
	echo -e "\033[1;36m $msg \033[0m"
}

#在一个screen内创建任务
function addJob(){
	local screenName=$1
	local cmd

	cmd=$"cd /home/rrrbbbbreet"; 
	sendCmd $screenName "$cmd" #用引号防止传参被拆分成多个参数

	cmd=$"php report.php";  
	sendCmd $screenName "$cmd"
}

#发送一个命令给screen
function sendCmd(){
	local screenName=$1
	local cmd=$2
	screen -x -S $screenName -p 0 -X stuff "$cmd"  
	screen -x -S $screenName -p 0 -X stuff $'\n'
}

#停止一个screen
function stopScreen(){
	local screenName=$1
	msg "stop screen $screen_name"
	screen -X -S $screenName -p 0 -X stuff $'\003'
	if [ $? -ne 0 ];then
		return
	fi

	local cmd=$"exit";
	sendCmd $screenName "$cmd"
}

#启动一个screen
function startScreen(){
	local screenName=$1
	msg "start screen $screen_name"
	if screen -ls|grep "\<$screenName\>" &>/dev/null;then
		echo "screen $screenName already running... "
		return
	fi
	screen -dmS $screenName
}

#usage
function usage(){
    echo $"Usage: $0 {start|stop|status}"
    exit 1
}

###################### main ########################
#位置参数
action=$1

#只允许一个位置参数
[ $# -ne 1 ] && usage

#控制多个screen
for id in `seq 1 $maxProc`; do
	#screen名字,后缀不能少
	screen_name=$"${scrPrefix}${id}J"  

	#根据控制指令决定做什么
	case "$action" in
		start)
			startScreen $screen_name
			addJob $screen_name
			;;
		stop)
			stopScreen $screen_name
			;;
		status)
			screen -ls
			exit 0
			;;
		*)
			usage
			;;
	esac
done

echo
#如果是启停控制，也打印一下status
if [ $action = "start" -o $action = "stop" ];then
	msg "$action screen result:"
	$0 status
fi